/**
 * 人脸识别功能测试工具
 * 用于测试人脸搜索API的各种参数和错误处理
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

import { searchFace, detectFace, convertImageToBase64 } from '../services/faceRecognitionService';

/**
 * 测试人脸识别功能
 * @param {File} imageFile 测试图片文件
 * @param {Object} options 测试选项
 */
export const testFaceRecognition = async (imageFile, options = {}) => {
  const testResults = {
    timestamp: new Date().toISOString(),
    imageFile: {
      name: imageFile.name,
      size: imageFile.size,
      type: imageFile.type
    },
    tests: []
  };

  try {
    // 转换图片为Base64
    const base64Image = await convertImageToBase64(imageFile);
    testResults.base64Length = base64Image.length;

    // 测试1: 人脸检测
    console.log('🔍 开始人脸检测测试...');
    const detectResult = await detectFace(base64Image);
    testResults.tests.push({
      name: '人脸检测',
      success: detectResult.success,
      error: detectResult.error,
      data: detectResult.data
    });

    if (!detectResult.success) {
      console.error('❌ 人脸检测失败:', detectResult.error);
      return testResults;
    }

    const faceList = detectResult.data.face_list;
    if (!faceList || faceList.length === 0) {
      console.error('❌ 未检测到人脸');
      testResults.tests.push({
        name: '人脸检测结果',
        success: false,
        error: '未检测到人脸'
      });
      return testResults;
    }

    const face = faceList[0];
    console.log('✅ 人脸检测成功:', {
      age: face.age,
      gender: face.gender?.type,
      expression: face.expression?.type,
      quality: face.quality
    });

    // 测试2: 不同质量控制级别的人脸搜索
    const qualityLevels = ['NONE', 'LOW', 'NORMAL', 'HIGH'];
    for (const quality of qualityLevels) {
      console.log(`🔍 测试质量控制级别: ${quality}`);
      const searchResult = await searchFace(base64Image, {
        qualityControl: quality,
        livenessControl: 'NORMAL',
        spoofingControl: 'NORMAL',
        maxUserNum: 1,
        matchThreshold: 80
      });

      testResults.tests.push({
        name: `人脸搜索-质量控制${quality}`,
        success: searchResult.success,
        error: searchResult.error,
        errorType: searchResult.errorType,
        data: searchResult.data
      });

      if (searchResult.success) {
        console.log(`✅ ${quality}级别搜索成功:`, searchResult.data);
      } else {
        console.log(`❌ ${quality}级别搜索失败:`, searchResult.error);
      }
    }

    // 测试3: 不同活体检测级别
    const livenessLevels = ['NONE', 'LOW', 'NORMAL', 'HIGH'];
    for (const liveness of livenessLevels) {
      console.log(`🔍 测试活体检测级别: ${liveness}`);
      const searchResult = await searchFace(base64Image, {
        qualityControl: 'NORMAL',
        livenessControl: liveness,
        spoofingControl: 'NORMAL',
        maxUserNum: 1,
        matchThreshold: 80
      });

      testResults.tests.push({
        name: `人脸搜索-活体检测${liveness}`,
        success: searchResult.success,
        error: searchResult.error,
        errorType: searchResult.errorType,
        data: searchResult.data
      });

      if (searchResult.success) {
        console.log(`✅ ${liveness}级别活体检测成功:`, searchResult.data);
      } else {
        console.log(`❌ ${liveness}级别活体检测失败:`, searchResult.error);
      }
    }

    // 测试4: 不同匹配阈值
    const thresholds = [0, 50, 70, 80, 90];
    for (const threshold of thresholds) {
      console.log(`🔍 测试匹配阈值: ${threshold}`);
      const searchResult = await searchFace(base64Image, {
        qualityControl: 'NORMAL',
        livenessControl: 'NORMAL',
        spoofingControl: 'NORMAL',
        maxUserNum: 1,
        matchThreshold: threshold
      });

      testResults.tests.push({
        name: `人脸搜索-匹配阈值${threshold}`,
        success: searchResult.success,
        error: searchResult.error,
        errorType: searchResult.errorType,
        data: searchResult.data
      });

      if (searchResult.success) {
        console.log(`✅ 阈值${threshold}搜索成功:`, searchResult.data);
      } else {
        console.log(`❌ 阈值${threshold}搜索失败:`, searchResult.error);
      }
    }

  } catch (error) {
    console.error('❌ 测试过程中发生错误:', error);
    testResults.tests.push({
      name: '测试异常',
      success: false,
      error: error.message
    });
  }

  return testResults;
};

/**
 * 生成测试报告
 * @param {Object} testResults 测试结果
 */
export const generateTestReport = (testResults) => {
  const report = {
    summary: {
      totalTests: testResults.tests.length,
      successCount: testResults.tests.filter(t => t.success).length,
      failureCount: testResults.tests.filter(t => !t.success).length,
      successRate: 0
    },
    details: testResults.tests,
    recommendations: []
  };

  report.summary.successRate = (report.summary.successCount / report.summary.totalTests * 100).toFixed(2);

  // 生成建议
  const failures = testResults.tests.filter(t => !t.success);
  if (failures.length > 0) {
    const qualityFailures = failures.filter(f => f.errorType === 'quality');
    const livenessFailures = failures.filter(f => f.errorType === 'liveness');
    const spoofingFailures = failures.filter(f => f.errorType === 'spoofing');

    if (qualityFailures.length > 0) {
      report.recommendations.push('建议降低质量控制级别或改善图片质量');
    }
    if (livenessFailures.length > 0) {
      report.recommendations.push('建议降低活体检测级别或使用真人照片');
    }
    if (spoofingFailures.length > 0) {
      report.recommendations.push('建议降低合成图检测级别或使用真实照片');
    }
  }

  return report;
};

/**
 * 在控制台输出测试报告
 * @param {Object} testResults 测试结果
 */
export const printTestReport = (testResults) => {
  const report = generateTestReport(testResults);
  
  console.log('\n📊 人脸识别功能测试报告');
  console.log('='.repeat(50));
  console.log(`测试时间: ${testResults.timestamp}`);
  console.log(`图片文件: ${testResults.imageFile.name} (${(testResults.imageFile.size / 1024).toFixed(2)}KB)`);
  console.log(`Base64长度: ${testResults.base64Length}`);
  console.log(`总测试数: ${report.summary.totalTests}`);
  console.log(`成功数: ${report.summary.successCount}`);
  console.log(`失败数: ${report.summary.failureCount}`);
  console.log(`成功率: ${report.summary.successRate}%`);
  
  if (report.recommendations.length > 0) {
    console.log('\n💡 建议:');
    report.recommendations.forEach(rec => console.log(`- ${rec}`));
  }
  
  console.log('\n📋 详细结果:');
  testResults.tests.forEach(test => {
    const status = test.success ? '✅' : '❌';
    console.log(`${status} ${test.name}: ${test.success ? '成功' : test.error}`);
  });
  
  console.log('='.repeat(50));
};

export default {
  testFaceRecognition,
  generateTestReport,
  printTestReport
};

